#include "dswconsole_gprs_session_base.h"

CDswconsole_gprs_session_base::CDswconsole_gprs_session_base(LPST_ENV_T pEnv, struct bufferevent *pBev)
: m_pEnv(pEnv)
, m_pBev(pBev)
, m_nSocketIndex(0)
, m_nPushCount(0)
{
	m_nTask_Push.ev = NULL;
	memset(&m_nGprsSendData, 0, sizeof(m_nGprsSendData));
}

CDswconsole_gprs_session_base::~CDswconsole_gprs_session_base()
{
	CLEAR_GPRS_DATA(m_nGprsSendData);
	CLEAR_EV(m_nTask_Push);
}

void CDswconsole_gprs_session_base::MakeGPRSSendData(int nSocketIndex, char* pData, int nLen)
{
	CLEAR_GPRS_DATA(m_nGprsSendData);
	m_nGprsSendData.nSocketIndex = nSocketIndex;
	m_nGprsSendData.pData = new char[nLen + (nLen % sizeof(int))];
	m_nGprsSendData.nLen = nLen;
	memcpy(m_nGprsSendData.pData, pData, nLen);
	m_nGprsSendData.pSendPos = m_nGprsSendData.pData;
	m_nGprsSendData.nSendedLen = 0;
}

void CDswconsole_gprs_session_base::SendTcpData(LPST_GPRS_DATA_T pGprsData)
{
	int nLeftLen = 0;
	if (pGprsData->nLen > MAX_GPRS_TCP_SENDLEN)
		nLeftLen = MAX_GPRS_TCP_SENDLEN;
	else if (pGprsData->nLen > 0)
		nLeftLen = pGprsData->nLen;

	pGprsData->nSendedLen = 0;
	if (nLeftLen > 0){
		char sBuffer[1024];
		char *pDestPos;
		pDestPos = sBuffer;
		sprintf(pDestPos, "at+mipsend=%d,\"", pGprsData->nSocketIndex);
		pDestPos += strlen(pDestPos);
		int i;
		for (i = 0; i < nLeftLen; i++){
			sprintf(pDestPos, "%02x", pGprsData->pSendPos[i]);
			pDestPos += 2;
			pGprsData->nSendedLen++;
		}
		sprintf(pDestPos, "\",0\r\n");
		pDestPos += strlen("\",0\r\n");
//		printf("9999999999 = %s\n", sBuffer);
		SendData(sBuffer, pDestPos - sBuffer);
	}
}

void CDswconsole_gprs_session_base::OnGPRSSendedData(int nState)
{
	if (nState != 0)
		SendTcpData(&m_nGprsSendData);
	else{
		char sBuffer[256];
		sprintf(sBuffer, "at+mippush=%d\r\n", m_nSocketIndex);
		SendData(sBuffer, strlen(sBuffer));
	}
}

void CDswconsole_gprs_session_base::OnGPRSPushedData(int nState)
{
	if ((nState == 0) || (nState == 2)){
		m_nGprsSendData.nLen -= m_nGprsSendData.nSendedLen;
		m_nGprsSendData.pSendPos += m_nGprsSendData.nSendedLen;
		m_nGprsSendData.nSendedLen = 0;
		if (m_nGprsSendData.nLen > 0)
			SendTcpData(&m_nGprsSendData);
		else{
			CLEAR_GPRS_DATA(m_nGprsSendData);
		}
		if (m_nTask_Push.ev){
			CLEAR_EV(m_nTask_Push);
		}
		m_nPushCount = 0;
	}
	else{
		m_nPushCount++;
		if (m_nTask_Push.ev){
			TRIG_EV(m_nTask_Push, 5, 0);
		}
		else{
			CREATE_EV(m_nTask_Push, 5, 0, m_pEnv->pEvBase, CDswconsole_gprs_session_base::cbPushTaskFunc, this);
		}
	}
}

void CDswconsole_gprs_session_base::PushTaskFunc(int fd, short events)
{
	if (m_nPushCount > 6){
		printf("ffffffffffffff\n");
		OnCommTimeOut();
	}
	else{
		char sBuffer[256];
		sprintf(sBuffer, "at+mippush=%d\r\n", m_nSocketIndex);
		SendData(sBuffer, strlen(sBuffer));
		printf("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz = %s\n", sBuffer);
	}
}

